﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using DotNetNuke.Services.Installer;
using System.IO;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Common.Utilities;
using System.Xml;
using System.Xml.XPath;
using DotNetNuke.UI.Skins;
namespace Spiffy.DatabaseMonitor
{
    public partial class view : DotNetNuke.Entities.Modules.PortalModuleBase
    {
        protected void Page_Load(object sender, EventArgs e)
        { 
           
            if (!Page.IsPostBack)
            {

                XmlDocument TargetConfig = new XmlDocument();
                TargetConfig.Load(Path.Combine(Server.MapPath("~"), "web.config"));

                if (TargetConfig.SelectSingleNode("/configuration/system.webServer/modules/add[@name='SpiffyDatabaseMonitor']") != null)
                {
                    btnDisable.Visible = true;
                    btnEnable.Visible = false;

                }
                else {
                    btnDisable.Visible = false;
                    btnEnable.Visible = true;
                }


                if (Settings["SendEmail"] != null)
                {
                    cbSendEmail.Checked = Convert.ToBoolean(Settings["SendEmail"]);
                }
                else 
                { 
                    cbSendEmail.Checked = true; 
                }
                if (Settings["RetryTimer"] != null)
                {
                    tbRetryTimer.Text =Settings["RetryTimer"].ToString();
                }
                else
                {
                    tbRetryTimer.Text = "15000";
                }
            }
        }

        protected void btnEnable_Click(object sender, EventArgs e)
        {
            if (TestWebConfigWriteAccess())
            {
                try
                {
                    string ConfigString = "<configuration>" +
                                                        "<nodes configfile=\"web.config\">" +
                                                        "<node path=\"/configuration/system.web/httpModules/add[@name='RequestFilter']\" action=\"insertbefore\" key=\"name\" collision=\"ignore\">" +
                                                          "<add name=\"SpiffyDatabaseMonitor\" type=\"Spiffy.DatabaseMonitor.Monitor, Spiffy.DatabaseMonitor\" />" +
                                                        "</node>" +
                                                        "<node path=\"/configuration/system.webServer/modules/add[@name='RequestFilter']\" action=\"insertbefore\" key=\"name\" collision=\"ignore\">" +
                                                          "<add name=\"SpiffyDatabaseMonitor\" type=\"Spiffy.DatabaseMonitor.Monitor, Spiffy.DatabaseMonitor\" preCondition=\"managedHandler\" />" +
                                                        "</node>" +
                                                      "</nodes>" +
                                                    "</configuration>";

                    XmlDocument TargetConfig = new XmlDocument();
                    TargetConfig.Load(Path.Combine(Server.MapPath("~"), "web.config"));

                    if (TargetConfig.SelectSingleNode("/configuration/system.web/httpModules/add[@name='SpiffyDatabaseMonitor']") == null)
                    {
                        var merge = new XmlMerge(new StringReader(ConfigString), "", "");
                        merge.UpdateConfig(TargetConfig);
                        Config.Save(TargetConfig, "web.config");
                        btnEnable.Visible = false;
                        btnDisable.Visible = true;
                        Skin.AddModuleMessage(this, "Database monitor has been enabled.", DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.GreenSuccess);
                    }
                    else
                    {
                        Skin.AddModuleMessage(this, "Database monitor is already activated", DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
                        btnEnable.Visible = false;
                        btnDisable.Visible = true;
                    }
                }
                catch (Exception ex)
                {
                    DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
                    Skin.AddModuleMessage(this, "Error: HTTP Module has not been added. Module is not enabled.", DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
                }
            }
            
            
        }

        protected void btnDisable_Click(object sender, EventArgs e)
        {
            if (TestWebConfigWriteAccess())
            {

                try
                {
                    string ConfigString = "<configuration>" +
                                                       "<nodes configfile=\"web.config\">" +
                                                       "<node path=\"/configuration/system.web/httpModules/add[@name='SpiffyDatabaseMonitor']\" action=\"remove\" key=\"path\" collision=\"overwrite\" />" +
                                                       "<node path=\"/configuration/system.webServer/modules/add[@name='SpiffyDatabaseMonitor']\" action=\"remove\" key=\"name\" collision=\"overwrite\" />" +
                                                     "</nodes>" +
                                                   "</configuration>";

                    XmlDocument TargetConfig = new XmlDocument();
                    TargetConfig.Load(Path.Combine(Server.MapPath("~"), "web.config"));
                    var merge = new XmlMerge(new StringReader(ConfigString), "", "");
                    merge.UpdateConfig(TargetConfig);
                    Config.Save(TargetConfig, "web.config");
                    btnDisable.Visible = false;
                    btnEnable.Visible = true;
                    Skin.AddModuleMessage(this, "Database monitor has been disabled.", DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.GreenSuccess);
                }
                catch (Exception ex)
                {
                    DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
                    Skin.AddModuleMessage(this, "Error: Unable to remove HTTP Module.", DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
                } 
            }
            
        }

        protected bool TestWebConfigWriteAccess()
        {
            try
            {
                FileStream testWriteFS = File.OpenWrite(Path.Combine(Server.MapPath("~"), "web.config"));
                testWriteFS.Close();
                return true;

            }
            catch (Exception ex)
            {

                DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
                Skin.AddModuleMessage(this, "Error: Make sure web.config is not read-only.", DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
                return false;
            }
        }

        protected void btnSaveSettings_Click(object sender, EventArgs e)
        {
            ModuleController mc = new DotNetNuke.Entities.Modules.ModuleController();
            string retryTimer = "";
            
            if (tbRetryTimer.Text == "")
            {
                retryTimer = "15000";
            }
            else
            {
                retryTimer = tbRetryTimer.Text;
            }
  

            mc.UpdateModuleSetting(ModuleId, "RetryTimer", retryTimer);
            mc.UpdateModuleSetting(ModuleId, "SendEmail", cbSendEmail.Checked.ToString());

            Monitor.HostEmail = DotNetNuke.Entities.Host.Host.HostEmail;
            Monitor.HostTitle = DotNetNuke.Entities.Host.Host.HostTitle;

            Monitor.RetryTimer = Convert.ToInt32(retryTimer);
            Monitor.SendEmail = cbSendEmail.Checked;


            Skin.AddModuleMessage(this, "Settings have been updated.", DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.GreenSuccess);
        }

        
    }
}